import tkinter as tk
from tkinter import messagebox, simpledialog
import datetime
import threading
import time
import os
from playsound import playsound
import pystray
from PIL import Image, ImageDraw

alarms = []

def play_alarm():
    try:
        playsound("alarm.mp3")
    except Exception:
        pass

def alarm_thread():
    while True:
        now = datetime.datetime.now().strftime("%H:%M")
        for alarm in alarms:
            if not alarm['triggered'] and alarm['time'] == now:
                alarm['triggered'] = True
                messagebox.showinfo("闹钟提醒", alarm['msg'])
                play_alarm()
                if alarm['action'] == "关机":
                    os.system("shutdown /s /t 1")
                elif alarm['action'] == "执行脚本" and alarm['script']:
                    os.system(f"python {alarm['script']}")
        time.sleep(10)

def add_alarm():
    time_str = simpledialog.askstring("设置闹钟", "请输入闹钟时间（HH:MM）")
    if not time_str: return
    msg = simpledialog.askstring("自定义内容", "请输入提示内容")
    if not msg: msg = "时间到了！"
    action = simpledialog.askstring("动作", "到点执行（无/关机/执行脚本）")
    script = ""
    if action == "执行脚本":
        script = simpledialog.askstring("脚本路径", "请输入要执行的脚本路径")
    alarms.append({'time': time_str, 'msg': msg, 'triggered': False, 'action': action, 'script': script})
    update_alarm_list()

def remove_alarm():
    idx = alarm_list.curselection()
    if idx:
        alarms.pop(idx[0])
        update_alarm_list()

def update_alarm_list():
    alarm_list.delete(0, tk.END)
    for alarm in alarms:
        alarm_list.insert(tk.END, f"{alarm['time']} - {alarm['msg']} - {alarm['action']}")

def countdown():
    sec = simpledialog.askinteger("倒计时", "请输入倒计时秒数")
    if not sec: return
    def run():
        for i in range(sec, 0, -1):
            countdown_label.config(text=f"倒计时：{i} 秒")
            time.sleep(1)
        countdown_label.config(text="倒计时结束！")
        messagebox.showinfo("倒计时", "倒计时结束！")
        play_alarm()
    threading.Thread(target=run, daemon=True).start()

def stopwatch():
    running = True
    def run():
        t = 0
        while running:
            mins, secs = divmod(t, 60)
            stopwatch_label.config(text=f"秒表：{mins:02d}:{secs:02d}")
            time.sleep(1)
            t += 1
    def stop():
        nonlocal running
        running = False
        stopwatch_label.config(text="秒表已停止")
    threading.Thread(target=run, daemon=True).start()
    root.after(10000, stop)  # 10秒后自动停止（可自定义）

def on_quit(icon, item):
    icon.stop()
    root.quit()

def show_window(icon, item):
    root.after(0, root.deiconify)

def hide_window():
    root.withdraw()

def create_tray():
    image = Image.new('RGB', (64, 64), color=(255, 255, 255))
    d = ImageDraw.Draw(image)
    d.ellipse((16, 16, 48, 48), fill=(255, 0, 0))
    menu = (pystray.MenuItem('显示', show_window), pystray.MenuItem('退出', on_quit))
    icon = pystray.Icon("alarm", image, "闹钟", menu)
    threading.Thread(target=icon.run, daemon=True).start()

root = tk.Tk()
root.title("多功能桌面闹钟")
root.geometry("400x400")

tk.Button(root, text="添加闹钟", command=add_alarm).pack(pady=5)
tk.Button(root, text="删除选中闹钟", command=remove_alarm).pack(pady=5)
alarm_list = tk.Listbox(root)
alarm_list.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

tk.Button(root, text="倒计时", command=countdown).pack(pady=5)
countdown_label = tk.Label(root, text="")
countdown_label.pack()

tk.Button(root, text="秒表", command=stopwatch).pack(pady=5)
stopwatch_label = tk.Label(root, text="")
stopwatch_label.pack()

tk.Button(root, text="最小化到托盘", command=hide_window).pack(pady=5)

threading.Thread(target=alarm_thread, daemon=True).start()
create_tray()

root.protocol('WM_DELETE_WINDOW', hide_window)
root.mainloop()